import { createRouter, createWebHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import Login from '../views/Login.vue';
import superAdminRoutes from './superAdminRoutes';
import adminRoutes from './adminRoutes';
import adminRoutesNext from './GagentAdminRoutes'; 

import { useUserStore } from '@/stores/user';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/',
      name: 'layout',
      component: () => import('@/views/layout/index.vue'),
      children: []
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/404.vue')
    }
  ]
});

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  if (to.query.code) {
    const userStore = useUserStore();
    await userStore.getUserByCode(to.query.code);
    next('/');
  } else {
    // 登录页直接进入
    if (to.name === 'login') {
      next();
    } else {
      // 获取当前用户token
      let token = localStorage.getItem('token');
      if (token) {
        const userStore = useUserStore();
        if (!userStore.routes.length) {

          await userStore.getUser();
          let routesData = [];
          let { type, partnerLevel } = userStore.user;

          routesData = adminRoutes;
          if (partnerLevel === 'ONE'|| partnerLevel === 'GEN') {
            routesData = adminRoutesNext;
          }
          

          userStore.setRoutes(routesData);
          routesData.forEach(item => {
            router.addRoute('layout', item);
          });
          const routesDefault = router.getRoutes();
          routesDefault.map(item => {
            if (item.name === 'layout') {
              item.redirect = {
                name: routesData[0].name
              };
            }
          });

          next({
            path: to.path,
            query: to.query,
            replace: true
          });
        } else {
          next();
        }
      } else {
        const userStore = useUserStore();
        userStore.signOut();
        next({ path: '/login', query: { redirect: to.fullPath } });
      }
    }
  }
});

router.afterEach((to, from, next) => {
  NProgress.done();
});

export default router;
